<template>
  <el-container>
    <el-header>
      <div class="report_header" ref="headerHeight">
        <div class="report_header_left"></div>
        <div style="width: 300px;display: flex;align-items: center;margin-left: 10px;">
          <svg-icon class="primary" :icon-class="$route.meta.icon"/>
          <span style="margin-left: 5px;" class="primary">{{$route.meta.title}}</span>
        </div>
        <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
          <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px">

            <div class="report_header_query">
              <el-input prefix-icon="el-icon-search" placeholder="角色" v-model="query.name"></el-input>
            </div>
          </div>
          <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="querySysRole">查询</el-button>
          <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"
                     v-permission="['sysRole.add']">新增</el-button>
        </div>
      </div>
<!--      <div>-->
<!--        <svg-icon class="primary" :icon-class="$route.meta.icon"/>-->
<!--        <span class="primary">{{$route.meta.title}}</span>-->
<!--      </div>-->
<!--      <div class="header-button-container">-->
<!--        <el-button :icon="queryType? 'el-icon-search':'el-icon-close'" type="primary"-->
<!--                   @click="chooseClick">{{queryType == false?'隐藏':'查询'}}-->
<!--        </el-button>-->
<!--        <el-button v-permission="['sysRole.add']" icon="el-icon-plus" type="info" style="margin-left: 10px" @click="addClick">新增-->
<!--        </el-button>-->
<!--      </div>-->
    </el-header>
    <div class="pd10">
<!--      <div style="margin-bottom: 10px;display: flex;align-items: center" v-show="queryType == false">-->
<!--        <el-input prefix-icon="el-icon-search" placeholder="角色" style="width: 200px" v-model="query.name"></el-input>-->
<!--        <el-button style="margin-left: 10px" icon="el-icon-search" type="primary" @click="querySysRole">查询-->
<!--        </el-button>-->
<!--        <el-button style="margin-left: 10px" icon="el-icon-refresh-right" type="info" @click="resetSysRole">重置-->
<!--        </el-button>-->
<!--      </div>-->
      <el-table
        :data="sysRoleForm"
        border
        stripe
        v-loadMore="[payLoads,'sysRole-list']"
        :height="curHeight"
        style="width: 100%">
        <el-table-column
          type="index"
          width="50"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="角色"
          width="180"
          align="center"
          prop="name"
        >
        </el-table-column>
        <el-table-column
          label="状态"
          width="80"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == 0?'info':'success'">
              <span>{{scope.row.status | watchStatus}}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          align="left"
          prop="remark"
        >
        </el-table-column>
        <el-table-column
          label="功能"
          align="center"
          prop="remark"
          width="80"
          fixed="right"
        >
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="启用或停用" placement="top-start">
            <el-button v-permission="['sysRole.edit']" :loading="scope.row.loading" @click="openSysRole(scope.row)" type="primary" size="mini">{{scope.row.status == 0?'启用':'停用'}}</el-button>
          </el-tooltip>
        </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="80">
          <template slot-scope="scope">
            <div>
              <el-tooltip v-permission="['sysRole.edit']" class="item" effect="dark" content="编辑" placement="top-start">
                <a  @click="editClick(scope.row)">
                  <i style="color: #409EFF" class="el-icon-edit"></i>
                </a>
              </el-tooltip>
              <el-tooltip v-permission="['sysRole.del']" class="item" effect="dark" content="删除" placement="top-start">
                <a style="margin-left: 10px"  @click="deleteSysRole(scope.row)">
                  <i style="color: #F56C6C" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--新增角色-->
      <el-dialog title="新增角色" :visible.sync="dialogFormVisible">
        <el-container>
          <el-main class="popup_content">
            <el-form ref="addForm" :model="addForm" :rules="rules" label-width="80px" size="mini">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model="addForm.name"></el-input>
              </el-form-item>
              <el-form-item label="角色描述">
                <el-input v-model="addForm.remark"></el-input>
              </el-form-item>
            </el-form>
            <div
              style="padding: 20px;margin-bottom: 10px;border-radius: 3px;border: 1px solid #DCDFE6;height: 300px;overflow: auto">
              <el-tree highlight-current :data="data" show-checkbox :props="defaultProps" node-key="id" ref="tree"
                       @check-change="nodeClick">
            <span class="slot-t-node" slot-scope="{ node, data }">
                <i :class="{'el-icon-office-building primary': data.menuType==0, 'el-icon-school':data.menuType==1}"/>
                <span>{{ data.name }}</span>
            </span>
              </el-tree>
            </div>
          </el-main>
        </el-container>
        <div slot="footer" class="dialog-footer">
          <el-button  @click="dialogFormVisible = false">取 消</el-button>
          <el-button :loading="addClicked" type="primary" @click="saveSysRole('addForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!--编辑角色-->
      <el-dialog title="编辑角色" :visible.sync="editVisible">
        <el-container>
          <el-main class="popup_content">
            <el-form ref="editForm" :model="editForm" :rules="rules" label-width="80px" size="mini">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model="editForm.name"></el-input>
              </el-form-item>
              <el-form-item label="角色描述">
                <el-input v-model="editForm.remark"></el-input>
              </el-form-item>
            </el-form>
            <div
              style="padding: 20px;margin-bottom: 10px;border-radius: 3px;border: 1px solid #DCDFE6;height: 300px;overflow: auto">
              <el-tree highlight-current :data="data" show-checkbox :props="defaultProps" :default-checked-keys="defaultCheckedData" node-key="id"
                       ref="edittree"
                       @check-change="edit_nodeClick">
            <span class="slot-t-node" slot-scope="{ node, data }">
                <i :class="{'el-icon-office-building primary': data.menuType==0, 'el-icon-school':data.menuType==1}"/>
                <span>{{ data.name }}</span>
            </span>
              </el-tree>
            </div>
          </el-main>
        </el-container>
        <div slot="footer" class="dialog-footer">
          <el-button  @click="editVisible = false">取 消</el-button>
          <el-button :loading="editClicked" type="primary"  @click="updateSysRole('editForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <el-footer class="el-footerBox">
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="loadSysRole"></pagination>
    </el-footer>
  </el-container>
</template>

<script>
  import loadMore from '@/utils/loadMore.js'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import {list, del, find, save, update, updateRole} from '@/api/sysRole'
  import {list as treeList} from '@/api/sysMenu'
  import {getMenuTree} from '@/api/sysMch'
  import utils from '../../utils/utils.js'
  import Pagination from '@/components/Pagination';
  export default {
    name: 'sysRole-list',
    directives: { permission,loadMore},
    activated() {
      this.payLoads = new Date().getTime();
    },
    data() {
      return {
        payLoads:'',
        sysRoleForm: [],
        pageNum: 1,
        pageSize: 20,
        total: 0,
        queryType: true,
        query: {
          name: '',
        },
        keyword:{
          name:''
        },
        dialogFormVisible: false,
        addForm: {
          name: '',
          status: 0,
          remark: '',
        },
        clicked: false,
        data: [],
        defaultProps: {
          children: 'childrens',
          label: 'name'
        },
        defaultExpand: true,
        checked: false,
        addClicked: false,
        editClicked: false,
        menus: [],
        rules: {
          name: [
            {required: true, message: '请输入组织名称', trigger: 'blur'},
            {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
          ],
        },
        editVisible: false,
        editForm:{id: '', name: '', remark: ''},
        edit_menus: [],
        sysRoleOpenForm: {
          id: '',
          status: '',
        },
        defaultCheckedData:[],
        curHeight:null
      }
    },
    components: {Pagination},
    created() {
      this.loadSysRole()
      this.opentreeList()
    },
    filters: {
      watchStatus(val) {
        if (val == 1) {
          return '启用'
        } else {
          return '停用'
        }
      }
    },
    mounted(){
      this.comeIn()
      this.beforeMount()
    },
    methods: {
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            if (this.queryType == false) {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 266//减去页面上固定高度height
            } else {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 220//减去页面上固定高度height
            }
          })();
        };
      },
      comeIn(){
        console.log('222')
        var h = document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220//减去页面上固定高度height
      },
      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == false) {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 266//减去页面上固定高度height
        } else {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 220//减去页面上固定高度height
        }
      },
      deleteSysRole(data) {
        console.log(data)
        var _this = this;
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(data.id).then(response => {
            console.log(response)
            _this.sysRoleForm.forEach(function (item,index) {
              if (item.id == data.id){
                _this.sysRoleForm.splice(index,1)
              }
            });
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            });
          }).catch(error => {
            console.log('error!!')
          });
        }).catch(() => {

        })
      },
      querySysRole() {
        this.keyword = this.query;
        this.pageNum = 1
        this.loadSysRole()
      },
      resetSysRole() {
        this.query.name = '';
        this.keyword = this.query;
        this.pageNum = 1;
        this.loadSysRole()
      },
      loadSysRole() {
        var _this = this
        let params = new URLSearchParams();
        params.append('pageNum', _this.pageNum);
        params.append('pageSize', _this.pageSize);
        params.append('name', _this.keyword.name);
        list(params).then(response => {
          console.log(response)
          response.data.data.map(item => { return item.loading = false })
          _this.sysRoleForm = response.data.data
          _this.total = response.data.total
        }).catch(error => {
          console.log('error!!')
        });
      },

      //新增
      addClick() {
        this.addForm.name='';
        this.addForm.remark='';
        this.dialogFormVisible = true;
      },
      opentreeList() {
        let _this = this;
        let params = new URLSearchParams();
        //params.append('menuType', 0);
        getMenuTree(params).then(response => {
          console.log(response)
          _this.data = response.data;
        }).catch(error => {
          console.log('error!!')
        });
      },
      nodeClick() {
        var _this = this
        _this.menus = this.$refs.tree.getCheckedNodes().concat(this.$refs.tree.getHalfCheckedNodes())
      },
      saveSysRole(addForm) {
        var _this = this;

        this.$refs[addForm].validate((valid) => {
          if (valid) { // 校验表单
            _this.addClicked = true
            var menuList = []
            _this.menus.forEach(function (item) {
              menuList.push(item.id);
            });
            // let params = new URLSearchParams();
            //params.append('menuType', 0);
            _this.addForm.menus = menuList;
            save(_this.addForm).then(response => {
              console.log(response);
              _this.addClicked = false;
              _this.dialogFormVisible = false;
              _this.loadSysRole()
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              });
            }).catch(error => {
              _this.addClicked = false;
              console.log('error!!')
            });
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      //  编辑
      editClick(row) {
        this.editForm.id = row.id;
        this.findSysRole()
        this.editVisible = true
      },
      findSysRole() {
        var _this = this;
        let aaa = []
        console.log(_this.editForm.id)
        find(_this.editForm.id).then(response => {
          console.log(response)
          _this.editForm.name = response.data.sysRole.name;
          _this.editForm.remark = response.data.sysRole.remark;
          _this.defaultCheckedData = utils.cleanTree(_this.data,response.data.sysMenu)
          _this.$nextTick(() => {
            _this.$refs.edittree.setCheckedKeys(_this.defaultCheckedData);
          });
        }).catch(error => {
          console.log('error!!')
        });
      },
      edit_nodeClick() {
        var _this = this;
        _this.edit_menus = this.$refs.edittree.getCheckedNodes().concat(this.$refs.edittree.getHalfCheckedNodes())
        console.log(_this.edit_menus)
      },
      updateSysRole(editForm) {
        var _this = this
        this.$refs[editForm].validate((valid) => {
          if (valid) { // 校验表单
            _this.editClicked = true
            var menuList = []
            _this.edit_menus.forEach(function (item) {
              menuList.push(item.id);
            });
            _this.editForm.menus = menuList;
            update(_this.editForm).then(response => {
              console.log(response);
              _this.editClicked = false;
              _this.editVisible = false;
              _this.loadSysRole()
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              });
            }).catch(error => {
              _this.editClicked = false;
              console.log('error!!')
            });
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      openSysRole(row) {
        var _this = this
        console.log(row);
        row.loading = true
        this.sysRoleOpenForm.id = row.id;
        if (row.status == 0) {
          this.sysRoleOpenForm.status = 1
        } else if (row.status == 1) {
          this.sysRoleOpenForm.status = 0
        }
        updateRole(_this.sysRoleOpenForm).then(response => {
          console.log(response)
          _this.sysRoleForm.forEach(function (item) {
            if (item.id == row.id){
              item.status = response.data.status
            }
          })
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          });
          row.loading = false
        }).catch(error => {
          row.loading = false
          console.log('error!!')
        });
      },
    }
  }
</script>

<style scoped>

  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  /deep/ .el-dialog__header {
    border: 1px solid #eeeeee !important;
    padding: 15px !important;
  }

  /deep/ .el-dialog__body {
    padding: 0px 20px !important;
  }
  .popup_content{
    padding-bottom: 0px !important;
  }
  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }
  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
</style>
